package com.ddd.mill.infrastructure.persistent.repository.impl.product;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ddd.mill.domain.aggregate.product.entity.ProductImg;
import com.ddd.mill.domain.aggregate.product.repository.ProductImgRepository;
import com.ddd.mill.infrastructure.exception.BizException;
import com.ddd.mill.infrastructure.persistent.dao.product.ProductImgDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author liu
 * @title: ProductImgMyBatisRepositoryImpl
 * @projectName trading-center
 * @date 2020/11/3010:24
 */
@Component
@Slf4j
public class ProductImgMyBatisRepositoryImpl implements ProductImgRepository {
    @Resource
    ProductImgDao dao;
    @Override
    public ProductImg load(Long id) {
        return dao.selectById(id);
    }

    @Override
    public Long save(ProductImg entity) {
        if (!Objects.isNull(entity.getId()) && !Objects.isNull(dao.selectById(entity.getId()))) {
            dao.updateById(entity);
        } else {
            dao.insert(entity);
        }
        return entity.getId();
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<ProductImg> productImgList) {
        try{
            for (ProductImg productImg:productImgList){
                dao.insert(productImg);
            }
        }catch (Exception e){
            throw new BizException("保存失败");
        }
    }

    @Override
    public List<ProductImg> getListByProductId(Long id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("product_id", id);
        return dao.selectList(queryWrapper);
    }
}
